package com.datasure.application.service.impl;

import com.datasure.application.req.event.SaveTaskEvent;
import com.datasure.application.service.MoveTaskService;
import com.datasure.domain.entity.Device;
import com.datasure.domain.entity.DiskClone;
import com.datasure.domain.entity.DiskCloneEx;
import com.datasure.domain.entity.Harddisk;
import com.datasure.domain.service.MoveTaskDomainService;
import com.datasure.external.MsgSendServce;
import com.datasure.repository.*;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.util.List;

/**
 * @author zhangxiaolong
 * @ClassName MoveTaskServiceImpl.java
 * @Description
 * @createTime 2022年02月09日 17:17:00
 */
public class MoveTaskServiceImpl implements MoveTaskService {

    private DeviceRepository deviceRepository;
    private DiskCloneRepository diskCloneRepository;
    private DiskCloneExRepository diskCloneExRepository;
    private HardDiskRepository hardDiskRepository;
    private PartitionRepository partitionRepository;
    private VolumeRepository volumeRepository;

    //外部依赖，消息服务器推送
    private MsgSendServce msgSendServce;

    private MoveTaskDomainService moveTaskDomainService;


    /**
     * 保存迁移任务配置
     * @param saveTaskEvent
     * @return
     */
    @Transactional
    public String saveTask(@Valid SaveTaskEvent saveTaskEvent){
        //涉及到需要持久化的对象先查询出来，传入到领域服务中
        Device sourceDevice = deviceRepository.find(saveTaskEvent.getSourceDeviceId());
        Device targetDevice = deviceRepository.find(saveTaskEvent.getTargetDeviceId());
        DiskClone sourceDiskClone = diskCloneRepository.findByDeviceId(saveTaskEvent.getSourceDeviceId());
        DiskCloneEx sourceDiskCloneEx = diskCloneExRepository.find(sourceDiskClone.getDiskcloneId());

        Harddisk sourceHarddisk = new Harddisk(sourceDevice.getDeviceId());

        //领域服务 操作实体对象
        moveTaskDomainService.buildMoveTask(sourceDevice, targetDevice, sourceDiskClone, sourceDiskCloneEx, sourceHarddisk);

        //实体对象持久化
        deviceRepository.save(sourceDevice);
        deviceRepository.save(targetDevice);
        diskCloneRepository.save(sourceDiskClone);
        diskCloneExRepository.save(sourceDiskCloneEx);
        hardDiskRepository.updateByDeviceId(sourceDevice.getDeviceId());

        //配置通过消息服务器下发到客户端，
        msgSendServce.issuedMoveTaskConfig(sourceDevice, sourceDiskClone);

        return "";
    }
}
